import axios from 'axios'
import store from '../store'
import { isCheckTimeout } from './auth'
import Router from '../router'
import { ElMessage } from 'element-plus'
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000 // request timeout
  timeout: 20000 // request timeout
})
// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 在这里全局注入token
    if (store.getters.accessToken) {
      if (isCheckTimeout()) {
        store.dispatch('user/logout')
        return Promise.reject(new Error('token 失效'))
      }
      config.headers!.Authorization = `Bearer ${store.getters.accessToken}`
    }
    config.headers!['Accept-Language'] = store.getters.language
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
let isRefreshing = false // 标记是否正在刷新 token
let requests = <any>[] // 存储待重发请求的数组
// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const { config, status } = response
    if (response.headers['session-status']) {
      store.dispatch('user/logout')
      return
    }
    // TODO 对响应 token过期,非法token,其他客户端登录响应状态码进行处理
    const { success, message, data, exception } = response.data
    if (success) {
      if (data === undefined) ElMessage.success(message)
      else return data
    } else {
      if (response.headers['content-type'] === 'text/xml;charset=utf-8') {
        if (status === 200 && response.data !== undefined) {
          return response.data
        }
      }
      // TODO 失败(请求成功,业务失败),消息提示
      if (exception) {
        console.log(exception)
      }
      switch (data.code) {
        case 20006:
          if (!isRefreshing) {
            isRefreshing = true
            return store
              .dispatch('user/refreshToken', { refreshToken: store.getters.refreshToken })
              .then(() => {
                // token 刷新后将数组的方法重新执行
                requests.forEach((cb: () => {}) => cb())
                requests = <any>[]
                return service(config)
              })
              .catch((err: any) => {
                store.dispatch('user/resetSite')
                // console.log('抱歉，您的登录状态已失效，请重新登录！')
                // return Promise.reject(err)
              })
              .finally(() => {
                isRefreshing = false
              })
          } else {
            // 返回未执行 resolve 的 Promise
            return new Promise((resolve) => {
              // 用函数形式将 resolve 存入，等待刷新后再执行
              requests.push(() => {
                resolve(service(config))
              })
            })
          }
          return Promise.reject(data)
          // return response && response.data
          break
        case 20007:
        case 20010:
          break
        case 20009:
        case 20012:
          ElMessage.error(message)
          store.dispatch('user/resetSite')
          break
        default:
          console.log(data.code)
          ElMessage.error(message)
          return Promise.reject(new Error(message))
      }
    }
  },
  // 请求失败
  (e: any) => {
    switch (e.response.status) {
      case 401:
        ElMessage.error(e.response.data.message)
        Router.push('/401')
        break
      case 500:
        ElMessage.error(e.response.data.message)
        break
      default:
        return Promise.reject(e)
    }
  }
)
export default service
